package org.dfl.plugin.autoalign;

import org.dfl.core.model.Place;
import org.dfl.core.model.TInputEdge;
import org.dfl.core.model.TOutputEdge;
import org.dfl.plugin.editor.figures.FiguresConstants;
import org.dfl.plugin.editor.model.DflDiagram;
import org.dfl.plugin.editor.model.PlaceModelElement;
import org.dfl.plugin.editor.model.TransitionModelElement;
import org.eclipse.swt.graphics.FontData;

public class DotGenerator {
	String indent = "  ";
	DflDiagram diagram;
	String rankdir;
	String dot;
		
	public DotGenerator(DflDiagram diagram, boolean isTB) {
		this.diagram = diagram;
		rankdir = (isTB) ? "  rankdir=TB;\n" : "  rankdir=LR;\n";
		createDOT();
	}
	
	private void createDOT() {
		StringBuffer sb = new StringBuffer();
		sb.append("digraph G {\n");
		sb.append(rankdir);

		//listing all transition labels
		sb.append("\n");

		//get transition font data
		FontData fd = FiguresConstants.transitionFont.getFontData()[0];
		String fn = fd.getName();
		String fs = String.valueOf(fd.getHeight());
		
		sb.append(indent+"node [shape=box, fontname="+fn+"r, fontsize="+fs+"];\n");
		for (TransitionModelElement transitionME : diagram.getTransitions())
			sb.append(indent+indent+
					  "{node [label=\""+
					  transitionME.getLabelText()+
					  "\"] "+
					  transitionME.getId()+
					  ";}\n");

		//listing all place labels
		sb.append("\n");

		//get transition font data
		fd = FiguresConstants.transitionFont.getFontData()[0];
		fn = fd.getName();
		fs = String.valueOf(fd.getHeight());
		
		sb.append(indent+"node [shape=ellipse, fontname="+fn+", fontsize="+fs+"];\n");
		for (PlaceModelElement placeME : diagram.getPlaces())
			sb.append(indent+indent+"" +
					  "{node [label=\""+
					  placeME.getLabelText()+
					  "\"] "+
					  placeME.getId()+
					  ";}\n");
		
		//listing all edges
		for (PlaceModelElement placeME : diagram.getPlaces()) {
			Place place = placeME.getPlace();
			sb.append("\n");

			//first output edges of this place (i.e. input edges of some following transition)
			for (TInputEdge ie : place.getOutputEdges())
				sb.append(indent+
						  placeME.getId()+
						  "->"+
						  ie.getTransition().getId()+
						  ";\n");
/*						  " [label= \""+
						  ie.getLabel()+
						  "\"];\n");
*/			
			//then input edges this place (i.e. output edges of some preceding transition)
			for (TOutputEdge oe : place.getInputEdges())
				sb.append(indent+
						  oe.getTransition().getId()+
						  "->"+
						  placeME.getId()+
						  "\n");
		}

		sb.append("}\n");
		dot = sb.toString();
	}

	public String toString() {
		return dot;
	}
}
